package edu.cuit.avatar.net;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Executors;

/**
 * @author <a href="mailto:1020zhaodan@163.com">Adan</a>
 * @version 1.0
 * @date 2025/7/18 10:55
 *
 */
public class Server {
    public static final float PI = 3.14f;
    public static void main(String[] args) {
        //创建服务器端套接字(服务器程序)
        try(ServerSocket server = new ServerSocket(8848)){
            /*
            虚拟线程：轻量级的线程实现，目的在于显著的提高并发性能同时简化
                轻量级: 创建及切换开销极低
                高并发: 可以创建数百万个虚拟线程而不会耗尽系统资源
                兼容性: 与传统线程API兼容
                非绑定
             */
            var executor = Executors.newVirtualThreadPerTaskExecutor();
            while(true){ //服务器不停监听客户端的连接
                //监听客户端的连接
                Socket socket = server.accept(); //
                //一个客户端请求使用独立的线程进行处理给客户端进行响应
                executor.execute(new ResponseTask(socket));
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static class ResponseTask implements Runnable{
        private Socket socket;
        public ResponseTask(Socket socket){
            this.socket = socket;
        }
        @Override
        public void run() {
            try {
                System.out.println("建立连接客户端ip:" + socket.getInetAddress());
                //通过套接字进行数据传输
                var input = new DataInputStream(socket.getInputStream());
                var radius = input.readFloat();
                var area = PI * radius * radius;
                var output = new DataOutputStream(socket.getOutputStream());
                output.writeFloat(area);
                socket.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }


        }
    }
}
